package com.mm.serivce.user.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mm.domain.user.*;
import com.mm.mapper.user.*;
import com.mm.serivce.user.IDRoleService;
import com.mm.serivce.user.IDUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.util.common.CommonUtils;
import com.mm.vo.web.user.AuthMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-08-04
 */
@Service
public class DUserServiceImpl extends ServiceImpl<DUserMapper, DUser> implements IDUserService {

    private final IDRoleService roleService;

    private final DUserMapper userMapper;

    private final DRoleMapper roleMapper;

    private final DPermissionMapper permissionMapper;

    private final DLevelInfoMapper levelInfoMapper;

    private final DRolePermissionRelationMapper rolePermissionRelationMapper;

    private final DUserRoleRelationMapper userRoleRelationMapper;

    private final DUserPermissionRelationMapper userPermissionRelationMapper;

    public DUserServiceImpl(IDRoleService roleService, DUserMapper userMapper, DRoleMapper roleMapper, DPermissionMapper permissionMapper, DLevelInfoMapper levelInfoMapper, DRolePermissionRelationMapper rolePermissionRelationMapper, DUserRoleRelationMapper userRoleRelationMapper, DUserPermissionRelationMapper userPermissionRelationMapper) {
        this.roleService = roleService;
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.permissionMapper = permissionMapper;
        this.levelInfoMapper = levelInfoMapper;
        this.rolePermissionRelationMapper = rolePermissionRelationMapper;
        this.userRoleRelationMapper = userRoleRelationMapper;
        this.userPermissionRelationMapper = userPermissionRelationMapper;
    }


    @Override
    public Page<DUser> queryUserPage(Integer page, Integer limit, String userName) {
        Page<DUser> userIPage = new Page<>(page, limit);
        LambdaQueryWrapper<DUser> queryWrapper = new LambdaQueryWrapper<DUser>();
        if (StrUtil.isNotBlank(userName)) {
            queryWrapper.like(DUser::getUserName, userName);
        }
        queryWrapper.eq(DUser::getDelFlg, '0');
        userIPage = userMapper.selectPage(userIPage, queryWrapper);
        Optional.ofNullable(userIPage.getRecords()).orElse(new ArrayList<>())
                .forEach(u -> {
                    if (Objects.nonNull(u.getUserLevelId())) {
                        DLevelInfo levelInfo = levelInfoMapper.selectById(u.getUserLevelId());
                        if (Objects.nonNull(levelInfo)) {
                            u.setUserLeveName(levelInfo.getLevelName());
                        }
                    }
                    List<DRole> roleList = roleService.queryRoleList(u.getUserId());
                    u.setRoles(roleList);
                    if (u.getRoles().size() > 0) {
                        List<String> roleIds = u.getRoles().stream().map(r -> String.valueOf(r.getRoleId()))
                                .collect(Collectors.toList());
                        String roleIdStr = roleIds.stream().collect(Collectors.joining(","));
                        u.setRoleIds(roleIdStr);
                    }
                });

        userIPage.setTotal(userIPage.getRecords().size());
        return userIPage;
    }

    @Override
    public List<DUser> queryUserAll() {
        List<DUser> userList = new ArrayList<>();
        // 查询司机角色和用户的关系
        LambdaQueryWrapper<DUserRoleRelation> queryURWrapper = new LambdaQueryWrapper<DUserRoleRelation>();
        queryURWrapper.eq(DUserRoleRelation::getRoleId, "2");
        List<DUserRoleRelation> urList = userRoleRelationMapper.selectList(queryURWrapper);
        List<Integer> userIds = new ArrayList<>();
        if (urList.size() > 0) {
            userIds = urList.stream().map(r -> r.getUserId()).collect(Collectors.toList());
            LambdaQueryWrapper<DUser> queryUWrapper = new LambdaQueryWrapper<DUser>();
            queryUWrapper.in(DUser::getUserId, userIds);
            userList = userMapper.selectList(queryUWrapper);
        }
        return userList;
    }

    @Override
    public boolean removeUser(Integer userId) {
        boolean flag = false;
        DUser userInfo = userMapper.selectById(userId);
        if (Objects.nonNull(userInfo)) {
            userInfo.setDelFlg(1);
            Integer result = userMapper.updateById(userInfo);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public DUser findUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public DUser findUserByAccountPwd(String userName, String Password) {
        LambdaQueryWrapper<DUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DUser::getUserAccount, userName);
        queryWrapper.eq(DUser::getUserPassword, Password);
        queryWrapper.eq(DUser::getDelFlg, "0");
        DUser user = userMapper.selectOne(queryWrapper);
        if (Objects.nonNull(user)) {
            // 查询用户角色
            LambdaQueryWrapper<DUserRoleRelation> queryURWrapper = new LambdaQueryWrapper();
            queryURWrapper.eq(DUserRoleRelation::getUserId, user.getUserId());
            List<DUserRoleRelation> userRoleRelations = userRoleRelationMapper.selectList(queryURWrapper);

            List<Integer> roleIds = userRoleRelations.stream().map(rp -> rp.getRoleId()).collect(Collectors.toList());
            LambdaQueryWrapper<DRole> queryRWrapper = new LambdaQueryWrapper();
            queryRWrapper.in(DRole::getRoleId, roleIds);
            List<DRole> roles = roleMapper.selectList(queryRWrapper);
            user.setRoles(roles);
            // 查询用户权限
            LambdaQueryWrapper<DRolePermissionRelation> queryRPWrapper = new LambdaQueryWrapper();
            queryRPWrapper.in(DRolePermissionRelation::getRoleId, roleIds);
            List<DRolePermissionRelation> rolePermissionRelations = rolePermissionRelationMapper.selectList(queryRPWrapper);

            List<Integer> permissIds = rolePermissionRelations.stream().map(rp -> rp.getPId()).collect(Collectors.toList());
            LambdaQueryWrapper<DPermission> queryPWrapper = new LambdaQueryWrapper();
            queryPWrapper.in(DPermission::getPId, permissIds);
            List<DPermission> permisss = permissionMapper.selectList(queryPWrapper);
            // 递归查询权限菜单
            permisss = permisss.stream().distinct().collect(Collectors.toList());
            permisss = CommonUtils.mergeMenuList(permisss);
            user.setPermissions(permisss);
        }
        return user;
    }

    @Override
    public DUser registerUser(String registerUsername, String registerPassword, String selectValue) {
        // 验证账户是否存在
        LambdaQueryWrapper<DUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DUser::getUserAccount, registerUsername);
        queryWrapper.eq(DUser::getDelFlg, "0");
        DUser user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            // 新增用户
            user = DUser.builder().userName(registerUsername)
                    .userAccount(registerUsername)
                    .userPassword(registerPassword)
                    .userLevelId(1).userSex(2).build();
            userMapper.insert(user);
            // 新增用户角色关系 2-司机 3-乘客
            DUserRoleRelation relation = DUserRoleRelation.builder()
                    .roleId(Integer.parseInt(selectValue))
                    .userId(user.getUserId()).build();
            userRoleRelationMapper.insert(relation);
        }
        return user;
    }

    @Override
    public boolean bindAuthMenu(AuthMenuVo vo) {
        Integer result = 0;
        // 绑定用户角色权限;删除该用户对应的角色菜单
        LambdaQueryWrapper<DUserRoleRelation> queryURWrapper = new LambdaQueryWrapper();
        queryURWrapper.eq(DUserRoleRelation::getUserId, vo.getUserId());
        result = userRoleRelationMapper.delete(queryURWrapper);
        LambdaQueryWrapper<DUserPermissionRelation> queryUPWrapper = new LambdaQueryWrapper();
        queryUPWrapper.eq(DUserPermissionRelation::getUserId, vo.getUserId());
        result = userPermissionRelationMapper.delete(queryUPWrapper);
        // 新增用户角色权限关系
        List<DUserRoleRelation> roleRelations = new ArrayList<>();
        List<Integer> roleIds = vo.getRoleIds();
        for (int i = 0; i < roleIds.size(); i++) {
            roleRelations.add(DUserRoleRelation.builder()
                    .userId(vo.getUserId())
                    .roleId(roleIds.get(i))
                    .build());
        }
        result = userRoleRelationMapper.insertBatchSomeColumn(roleRelations);
        List<DUserPermissionRelation> userPermissionRelations = new ArrayList<>();
        List<Integer> pIds = vo.getPIds();
        for (int i = 0; i < pIds.size(); i++) {
            userPermissionRelations.add(DUserPermissionRelation.builder()
                    .userId(vo.getUserId())
                    .pId(pIds.get(i))
                    .build());
        }
        result = userPermissionRelationMapper.insertBatchSomeColumn(userPermissionRelations);
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }


}
